<template>
  <div class="container" v-loading="loading">
    <div class="card">
      <div class="operate">
        <div class="search">
          <div>部门搜索</div>
          <div>
            <el-tree-select v-model="selectDept"
                            :data="deptTree"
                            :props="defaultProps"
                            check-strictly
                            :render-after-expand="false"
                            placeholder="请选择部门"/>
          </div>
          <div>人员搜索</div>
          <div>
            <el-input v-model="searchPerson"  placeholder="输入姓名">
              <template #prefix>
                <svg-icon name="search" size="15"></svg-icon>
              </template>
            </el-input>
          </div>
          <div>
            <el-button type="primary" @click="searchUser">查询</el-button>
          </div>
        </div>
        <div v-if="false">
          <el-button type="primary" @click="openPersonInfo">添加</el-button>
        </div>
        <el-pagination background layout="total, sizes, prev, pager, next"
                       :total="totalCount" :page-size="pageSize" :page-sizes="[50, 100, 150, 200, 250, 300]"
                       @size-change="handleSizeChange" @current-change="onPrevClick"/>
      </div>
      <div class="body">
        <el-tree class="department" :data="deptTree" empty-text="请添加部门信息后再添加人员信息"
                 :props="defaultProps" highlight-current @node-click="handleNodeClick" />
        <el-table class="person" :data="personData" border :key="needFlashData"
                  @row-dblclick = "editUser"
                  empty-text="请添加人员信息" style="width: 100%;height: 100%">
          <el-table-column type="index" label="序号" align="center" width="80"/>
          <el-table-column prop="username" label="姓名" align="center" min-width="100"/>
          <el-table-column prop="nickname" label="昵称" align="center" min-width="100"/>
          <el-table-column prop="roles" label="角色" align="center" width="100">
            <template #default="props">
              {{props.row.roles==='ROLE_USER' ? '普通用户': props.row.roles==='ROLE_USER,ROLE_CENSOR' ? '审核用户' : '管理员'}}
            </template>
          </el-table-column>
          <el-table-column prop="sex" label="性别" align="center" width="60">
            <template #default="props">
              {{props.row.sex===false ? '男':'女'}}
            </template>
          </el-table-column>
          <el-table-column prop="loginphone" label="手机号" align="center" width="120"/>
          <el-table-column prop="userphone" label="座机" align="center" width="120"/>
          <el-table-column prop="approver" label="审批员" align="center" width="80">
            <template #default="item">
              <el-switch v-model="item.row.approver" inline-prompt active-text="是" inactive-text="否" @change="enableApprover(item.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="operate" label="操作" align="center" width="120">
            <template #default="scope">
              <div  style="display: flex;justify-content: space-around">
                <el-link :underline="false" type="danger"  v-on:click="deleteOperate(scope.row)">删除</el-link>
                <el-link :underline="false" type="primary" v-on:click="updateOperate(scope.row)">修改</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <person-info @listenSubmit="onListenSubmit" @reload="reloadPerson"></person-info>
  </div>
</template>

<script lang="ts">
import {onMounted, ref} from "vue";
import {IDept} from "@/iwb/IConfig";
import {getDepartment} from "@/api/config";
import {IUser} from "@/iwb/IUser";
import PersonInfo from "@/components/PersonInfo.vue";
import {useConfigStore} from "@/store/config";
import {storeToRefs} from "pinia";
import {useUserStore} from "@/store/user";
import {Utils} from "@/utils/utils";

export default {
  name: "Person",
  components: {PersonInfo},
  setup() {
    const loading = ref(false);
    const deptOptions = ref([]);
    const needFlashData = ref(false);
    const searchPerson = ref('');
    const personData = ref([] as Array<IUser>)
    let currentDeptId = 0;
    const pageIndex = ref(0);
    const pageSize = ref(50);
    const totalCount = ref(0);

    const defaultProps = ref({
      children: 'children',
      label: 'name',
      value: 'id'
    })
    const deptTree = ref([] as Array<IDept>);
    /**
     * 选择过滤的部门
     */
    const selectDept = ref();
    const useConfig = useConfigStore();
    const {showPersonInfo} = storeToRefs(useConfig);

    const deleteOperate = (row: any) => {

    }

    const updateOperate = (row: IDept) => {
      editUser(row, null, null);
    }

    const reloadDeptTree = () => {
      loading.value = true;
      getDepartment().then((res: any) => {
        selectDept.value = 0;
        let root = {
              "id": 0,
              "name": "全体人员",
              "parentId": -1,
              "code": 0,
              "children": [] as Array<IUser>
            } as any;
        root.children.push(...res.data);
        deptTree.value.push(root) ;
        handleNodeClick(root, null);
        loading.value = false;
      }).catch(error => {
        console.error(error);
        loading.value = false;
      })
    }

    const handleNodeClick = (data: IDept, node: any) => {
      console.log(data);
      //console.log(node);
      /**
       * 获取当前部门ID
       */
      pageIndex.value = 0;
      totalCount.value = 0;
      const index = pageIndex.value;
      const size = pageSize.value;
      currentDeptId = data.id;
      const userStore = useUserStore();
      if (totalCount.value > index * size || pageIndex.value ===0) {
        userStore.queryUserByDeptId(pageIndex.value + 1, pageSize.value, currentDeptId).then((res: any) => {
          const { data } = res;
          totalCount.value = data.total;
          personData.value = res.data.users;
          pageIndex.value += 1;
          console.log(personData);
        })
      }
    }

    const onPrevClick = (value: number) => {
      console.log(value);
      const index = value - 1;
      const size = pageSize.value;
      pageIndex.value = index;
      const userStore = useUserStore();
      if (totalCount.value > index * size || pageIndex.value ===0) {
        userStore.queryUserByDeptId(pageIndex.value + 1, pageSize.value, currentDeptId).then((res: any) => {
          const { data } = res;
          totalCount.value = data.total;
          personData.value = res.data.users;
          pageIndex.value += 1;
          console.log(personData);
        })
      }
    }

    const handleSizeChange = (size: number) => {
      pageIndex.value = 0;
      totalCount.value = 0;
      const index = pageIndex.value;
      pageSize.value = size;
      const userStore = useUserStore();
      if (totalCount.value > index * size || pageIndex.value ===0) {
        userStore.queryUserByDeptId(pageIndex.value + 1, pageSize.value, currentDeptId).then((res: any) => {
          const { data } = res;
          totalCount.value = data.total;
          personData.value = res.data.users;
          pageIndex.value += 1;
          console.log(personData);
        })
      }
    }

    /**
     * 打开添加人员信息对话框
     */

    const openPersonInfo = () => {
      showPersonInfo.value = true;
    }

    const configStore = useConfigStore();
    const {personInfo} = storeToRefs(configStore);
    const editUser = (row: any, column: any, event: any) => {
      const cloneRow = Utils.cloneObject(row);
      showPersonInfo.value = true;
      personInfo.value = cloneRow;
      personInfo.value.sex = row.sex === true ? 1 : 0;
    }

    const enableApprover = (user: IUser) => {
      const userStore = useUserStore();
      userStore.setUserApprover([user.userId], user.approver).then(()=> {
        loading.value = false;
      }).catch(error=> {
        loading.value = false;
        console.error(error);
      });
    }

    const searchUser = () => {
      console.log(selectDept.value);
      console.log(searchPerson.value);

    }

    const reloadPerson = () => {
      /**
       * 获取当前部门ID
       */
      pageIndex.value = 0;
      totalCount.value = 0;
      const index = pageIndex.value;
      const size = pageSize.value;
      const userStore = useUserStore();
      if (totalCount.value > index * size || pageIndex.value ===0) {
        userStore.queryUserByDeptId(pageIndex.value + 1, pageSize.value, currentDeptId).then((res: any) => {
          const { data } = res;
          totalCount.value = data.total;
          personData.value = res.data.users;
          pageIndex.value += 1;
        })
      }
    }

    const onListenSubmit = (info: any) => {

    }

    onMounted(() => {
      reloadDeptTree();
    })

    return {
      loading,
      deptTree,
      personData,
      needFlashData,
      defaultProps,
      deptOptions,
      searchPerson,
      selectDept,
      pageSize,
      totalCount,
      deleteOperate,
      updateOperate,
      reloadDeptTree,
      handleNodeClick,
      onPrevClick,
      handleSizeChange,
      openPersonInfo,
      editUser,
      enableApprover,
      searchUser,
      reloadPerson,
      onListenSubmit
    }
  }
}
</script>

<style scoped lang="scss">
@import "src/styles/variable";
  .container {
    width: auto;
    height: 100%;
    padding: 10px;
    background-color: $color-background-base;
    border: 0;
    box-sizing: border-box;
  }
  .card {
    width: 100%;
    height: 100%;
    background-color: $color-sub-background-base;
    overflow: auto;
  }
  .operate {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid $color-border-base;
  }
  .search {
    display: flex;
    align-items: center;
    gap: 10px;
    color: $color-sub-text-base;
  }
  .body {
    display: flex;
    flex-direction: row;
    margin: 20px;
    height: calc(100% - 113px);

    .department {
      min-width: 200px;
    }
    .person {
      width: auto;
    }
    :deep(.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content) {
      background-color: $color-primary-base;
      color: $color-text-base;
    }
  }
</style>